import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

interface Role {
  id: number
  name: string
  description: string
  permissions: string[]
  createdAt?: string
  updatedAt?: string
}

interface RoleQueryParams {
  page: number
  limit: number
  name?: string
}

export const useRoleManagement = () => {
  // 角色管理相关的响应式数据
  const loading = ref(false)
  const saving = ref(false)
  const selectedRoles = ref<Role[]>([])
  const tableData = ref<Role[]>([])
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0
  })

  // 表单数据
  const editingRole = ref({
    id: 0,
    name: '',
    description: '',
    permissions: [] as string[]
  })

  const detailRole = ref({
    id: 0,
    name: '',
    description: '',
    permissions: [] as string[],
    createdAt: '',
    updatedAt: ''
  })

  // 查询参数
  const queryParams = reactive({
    page: 1,
    limit: 20,
    name: ''
  })

  // 加载角色列表
  const loadRoles = async () => {
    loading.value = true
    try {
      // 模拟API调用
      const response: any = {
        data: {
          list: [],
          pagination: {
            total: 0
          }
        }
      }
      
      if (response.data && response.data.list) {
        tableData.value = response.data.list
        pagination.total = response.data.pagination.total
      }
    } catch (error: any) {
      console.error('加载角色数据失败:', error)
      ElMessage.error('加载角色数据失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 搜索角色
  const handleSearch = () => {
    pagination.page = 1
    loadRoles()
  }

  // 重置搜索条件
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      limit: 20,
      name: ''
    })
    loadRoles()
  }

  // 处理选择变化
  const handleSelectionChange = (selection: Role[]) => {
    selectedRoles.value = selection
  }

  // 显示角色详情
  const showRoleDetail = async (role: Role) => {
    try {
      // 模拟API调用
      const response: any = {
        data: role
      }
      
      if (response.data) {
        detailRole.value = response.data
        return detailRole.value
      }
    } catch (error: any) {
      ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 编辑角色
  const editRole = async (role: Role) => {
    try {
      // 模拟API调用
      const response: any = {
        data: role
      }
      
      if (response.data) {
        editingRole.value = { ...response.data }
        return editingRole.value
      }
    } catch (error: any) {
      ElMessage.error('获取角色信息失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 保存角色（创建或更新）
  const saveRole = async () => {
    try {
      saving.value = true
      
      if (editingRole.value.id) {
        // 更新角色
        ElMessage.success('角色更新成功')
      } else {
        // 创建角色
        ElMessage.success('角色创建成功')
      }
      
      loadRoles()
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      saving.value = false
    }
  }

  // 删除角色
  const deleteRole = async (role: Role) => {
    try {
      // 模拟API调用
      ElMessage.success('删除成功')
      loadRoles()
      return true
    } catch (error: any) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 分页相关方法
  const handleSizeChange = (val: number) => {
    pagination.limit = val
    pagination.page = 1
    loadRoles()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    loadRoles()
  }

  return {
    // 数据
    loading,
    saving,
    selectedRoles,
    tableData,
    pagination,
    editingRole,
    detailRole,
    queryParams,
    
    // 方法
    loadRoles,
    handleSearch,
    handleReset,
    handleSelectionChange,
    showRoleDetail,
    editRole,
    saveRole,
    deleteRole,
    handleSizeChange,
    handleCurrentChange
  }
}